package com.ktjiaoyu.web.converter;

import com.alibaba.fastjson2.util.DateUtils;
import org.springframework.core.convert.converter.Converter;

import java.util.Date;

public class String2DateConverter implements Converter<String, Date> {
    private String[] dateFormats={
            "yyyy-MM-dd","yyyy-MM-dd HH:mm:ss","yyyy/MM/dd"
    };

    public void setDateFormats(String[] dateFormats){
        this.dateFormats=dateFormats;
    }

    @Override
    public Date convert(String source) {
        for (int i = 0; i < dateFormats.length; i++) {
            try {
                return DateUtils.parseDate(source,dateFormats[i]);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        throw new RuntimeException("日期格式转换失败，值为："+source);
    }
}
